// 创建一个新的修复后的顾客API文件

import request from '@/utils/request';
import { 
  Store, 
  Food, 
  Order, 
  Address, 
  Review, 
  CartItem, 
  PageParams, 
  PageResult,
  StoreQueryDTO,
  StoreSearchSort
} from '@/types/customer';

// 基础接口地址
const BASE_URL = '/api'; // 使用与商家端一致的API前缀，配合Vite代理使用

// 用户相关接口
export const userApi = {
  // 登录
  login: (data: { username: string; password: string }) =>
    request.post(`${BASE_URL}/auth/login`, {
      username: data.username,
      password: data.password,
    }),
    
  // 注册
  register: (data: { 
    username: string; 
    password: string; 
    phone?: string; 
    email?: string 
  }) =>
    request.post(`${BASE_URL}/auth/register`, {
      username: data.username,
      password: data.password,
      phone: data.phone || "",
      email: data.email || "",
      role: "USER",
    }),
    
  // 获取当前用户信息
  getProfile: () => request.get(`${BASE_URL}/users/profile`),
  
  // 更新用户信息
  updateProfile: (data: any) => request.put(`${BASE_URL}/users/profile`, data),
  
  // 上传用户头像
  uploadAvatar: (file: File) => {
    const formData = new FormData();
    formData.append('file', file);
    return request.post(`${BASE_URL}/users/avatar`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },
  
  // 删除用户头像
  deleteAvatar: (url: string) => {
    if (!url) {
      return Promise.reject(new Error("头像URL不能为空"));
    }
    return request.delete(`${BASE_URL}/users/avatar`, { params: { url } });
  },
  
  // 退出登录
  logout: () => request.post(`${BASE_URL}/auth/logout`),
};

// 收藏相关接口
export const favoriteApi = {
  // 获取收藏的店铺
  getFavoriteStores: (params?: { page?: number; size?: number }) =>
    request.get<Store[]>(`${BASE_URL}/favorites/stores`, { params }),
  
  // 获取收藏的食品
  getFavoriteFoods: (params?: { page?: number; size?: number }) =>
    request.get<Food[]>(`${BASE_URL}/favorites/foods`, { params }),
  
  // 收藏店铺
  addFavoriteStore: (storeId: number) =>
    request.post(`${BASE_URL}/favorites/stores`, {
      targetId: storeId,
    }),
  
  // 取消收藏店铺
  removeFavoriteStore: (storeId: number) =>
    request.delete(`${BASE_URL}/favorites/stores/${storeId}`),
  
  // 收藏食品
  addFavoriteFood: (foodId: number) =>
    request.post(`${BASE_URL}/favorites/foods`, {
      targetId: foodId,
    }),
  
  // 取消收藏食品
  removeFavoriteFood: (foodId: number) =>
    request.delete(`${BASE_URL}/favorites/foods/${foodId}`),
  
  // 检查店铺是否已收藏
  checkStoreFavorite: (storeId: number) =>
    request.get(`${BASE_URL}/favorites/stores/${storeId}`),
  
  // 检查商品是否已收藏
  checkFoodFavorite: (foodId: number) =>
    request.get(`${BASE_URL}/favorites/foods/${foodId}`),
};

// 历史记录接口
export const historyApi = {
  // 获取店铺浏览历史
  getStores: (params?: { page?: number; size?: number }) => 
    request.get<Store[]>(`${BASE_URL}/history/stores`, { params }),
  
  // 获取商品浏览历史  
  getFoods: (params?: { page?: number; size?: number }) => 
    request.get<Food[]>(`${BASE_URL}/history/foods`, { params }),
  
  // 添加店铺浏览历史
  addHistory: (storeId: number) =>
    request.post(`${BASE_URL}/history/stores`, {
      targetId: storeId,
    }),
  
  // 添加商品浏览历史
  addFoodHistory: (foodId: number) =>
    request.post(`${BASE_URL}/history/foods`, {
      targetId: foodId,
    }),
  
  // 删除浏览历史
  deleteHistory: (historyId: number) =>
    request.delete(`${BASE_URL}/history/${historyId}`)
};

// 用户设置接口
export const settingsApi = {
  // 更新用户密码
  updatePassword: (data: {
    oldPassword: string;
    newPassword: string;
  }) => 
    request.put(`${BASE_URL}/users/password`, data),
  
  // 退出登录
  logout: () => request.post(`${BASE_URL}/auth/logout`),
};

// 地址相关接口
export const addressApi = {
  // 获取地址列表
  getList: () => request.get(`${BASE_URL}/addresses`),
  
  // 获取单个地址详情
  getOne: (id: number) => 
    request.get(`${BASE_URL}/addresses/${id}`),
  
  // 添加地址
  add: (data: {
    receiver: string;
    phone: string;
    province: string;
    city: string;
    district: string;
    detailAddress: string;
    isDefault?: boolean;
  }) => 
    request.post(`${BASE_URL}/addresses`, data),
  
  // 更新地址
  update: (id: number, data: {
    receiver: string;
    phone: string;
    province: string;
    city: string;
    district: string;
    detailAddress: string;
    isDefault?: boolean;
  }) => 
    request.put(`${BASE_URL}/addresses/${id}`, data),
  
  // 删除地址
  delete: (id: number) => 
    request.delete(`${BASE_URL}/addresses/${id}`),
  
  // 设置默认地址
  setDefault: (id: number) => 
    request.post(`${BASE_URL}/addresses/${id}/default`),
};

// 商店相关接口
export const storeApi = {
  // 获取商店列表（使用新的DTO格式）
  getStores: (params?: StoreQueryDTO) => 
    request.get(`${BASE_URL}/stores`, { params }),
  
  // 获取商店详情
  getStoreDetail: (id: string) => 
    request.get(`${BASE_URL}/stores/${id}`),
  
  // 获取附近的商店
  getNearbyStores: (params: { latitude: number; longitude: number; radius?: number }) => 
    request.get(`${BASE_URL}/stores/nearby`, { params }),
  
  // 获取推荐商店
  getRecommended: (params?: StoreQueryDTO) => 
    request.get(`${BASE_URL}/stores/recommended`, { params }),
  
  // 获取店铺分类列表
  getCategories: () => 
    request.get(`${BASE_URL}/categories`),
  
  // 获取商店的食品类别
  getStoreCategories: (storeId: string) => 
    request.get(`${BASE_URL}/stores/${storeId}/categories`),
  
  // 搜索商店（与获取商店列表使用同一接口，通过参数区分）
  searchStores: (params: StoreQueryDTO) => 
    request.get(`${BASE_URL}/stores`, { params }),
  
  // 获取商店评价
  getStoreReviews: (storeId: string, params?: PageParams) => 
    request.get(`${BASE_URL}/stores/${storeId}/reviews`, { params })
};

// 食品相关接口
export const foodApi = {
  // 获取食品列表
  getFoods: (params?: PageParams) => 
    request.get<PageResult<Food>>(`${BASE_URL}/foods`, { params }),
  
  // 获取食品详情
  getFoodDetail: (id: string) => 
    request.get<Food>(`${BASE_URL}/foods/${id}`),
  
  // 获取商店的食品列表
  getStoreFoods: (storeId: string, params?: { categoryId?: string }) => 
    request.get<Food[]>(`${BASE_URL}/stores/${storeId}/foods`, { params }),
  
  // 获取推荐食品
  getRecommendFoods: (params?: PageParams) => 
    request.get<Food[]>(`${BASE_URL}/foods/recommend`, { params }),
  
  // 获取特色/特价食品
  getFeaturedFoods: (params?: PageParams) => 
    request.get<Food[]>(`${BASE_URL}/foods/featured`, { params }),
  
  // 搜索食品
  searchFoods: (params: PageParams) => 
    request.get<PageResult<Food>>(`${BASE_URL}/foods/search`, { params })
};

// 分类相关接口
export const categoryApi = {
  // 获取分类列表
  getCategories: () => 
    request.get(`${BASE_URL}/categories`),
  
  // 获取分类详情
  getCategoryDetail: (id: string) => 
    request.get(`${BASE_URL}/categories/${id}`),
  
  // 获取分类下的商店
  getCategoryStores: (categoryId: string, params?: PageParams) => 
    request.get<PageResult<Store>>(`${BASE_URL}/categories/${categoryId}/stores`, { params }),
  
  // 获取分类下的食品
  getCategoryFoods: (categoryId: string, params?: PageParams) => 
    request.get<PageResult<Food>>(`${BASE_URL}/categories/${categoryId}/foods`, { params })
};

// 购物车相关接口
export const cartApi = {
  // 获取所有购物车
  getCart: () => 
    request.get(`${BASE_URL}/cart`),
  
  // 获取店铺购物车
  getStoreCart: (storeId: number) => 
    request.get(`${BASE_URL}/cart/${storeId}`),
  
  // 添加到购物车
  addToCart: (data: { 
    storeId: number;
    foodId: number; 
    quantity: number; 
  }) => 
    request.post(`${BASE_URL}/cart`, data),
  
  // 更新购物车项
  updateCartItem: (itemId: number, data: { quantity: number }) => 
    request.put(`${BASE_URL}/cart/${itemId}`, data),
  
  // 从购物车移除商品
  removeFromCart: (itemId: number) => 
    request.delete(`${BASE_URL}/cart/item/${itemId}`),
  
  // 清空购物车
  clearCart: () => 
    request.delete(`${BASE_URL}/cart`),
  
  // 清空指定店铺购物车
  clearStoreCart: (storeId: number) => 
    request.delete(`${BASE_URL}/cart/${storeId}`),
};

// 订单相关接口
export const orderApi = {
  // 获取订单列表
  getOrders: (params?: { 
    status?: string; 
    page?: number; 
    size?: number; 
  }) => 
    request.get(`${BASE_URL}/orders`, { params }),
  
  // 获取订单详情 - 增加超时时间，因为可能需要聚合多个数据源
  getOrderDetail: (id: number) => 
    request.get(`${BASE_URL}/orders/${id}`, { 
      timeout: 15000, // 增加超时时间到15秒
      headers: {
        'Cache-Control': 'no-cache', // 避免缓存问题
      }
    }),
  
  // 创建订单
  createOrder: (data: { 
    storeId: number; 
    addressId: number; 
    remark?: string; 
  }) => 
    request.post(`${BASE_URL}/orders`, data),
  
  // 订单支付  
  payOrder: (data: { 
    orderId: number; 
    paymentType?: string; 
  }) => 
    request.post(`${BASE_URL}/orders/pay`, data),
  
  // 取消订单
  cancelOrder: (id: number) => 
    request.put(`${BASE_URL}/orders/${id}/cancel`),
  
  // 确认收货
  confirmOrder: (id: number) => 
    request.put(`${BASE_URL}/orders/${id}/confirm`),
  
  // 催单
  urgeOrder: (orderId: number) => 
    request.post(`${BASE_URL}/orders/${orderId}/urge`),
  
  // 评价订单
  reviewOrder: (id: number, data: { 
    content: string;
    storeRating: number;
    riderRating: number;
    images?: string; // 修改为 string 类型，后端期望的是字符串而不是数组
  }) => 
    request.post(`${BASE_URL}/orders/${id}/reviews`, data),
  
  // 获取骑手位置
  getRiderLocation: (orderId: number) => 
    request.get(`${BASE_URL}/orders/${orderId}/rider/location`),
};

// 导出便捷函数，方便直接调用
export const getRecommendStores = storeApi.getRecommended;
export const getFeaturedFoods = foodApi.getFeaturedFoods;
export const getCategories = categoryApi.getCategories;

// 为了向后兼容，保留一些常用的别名
export const getFavoriteStores = favoriteApi.getFavoriteStores;
export const getFavoriteFoods = favoriteApi.getFavoriteFoods;
export const addFavoriteStore = favoriteApi.addFavoriteStore;
export const removeFavoriteStore = favoriteApi.removeFavoriteStore;
export const checkFavoriteStore = favoriteApi.checkStoreFavorite; // 注意这里的方法名映射
export const addHistory = historyApi.addHistory;
